package com.daisyday.manage.gateway.common;

import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;

/**
 * 获取网络请求数据
 */
public class HttpService {
    /**
     * 获取网络请求ip
     * @param request
     * @return
     */
    public static String getIp(ServerHttpRequest  request) {
//        ServerHttpRequest request = (ServerHttpRequest)request1;
        HttpHeaders headers = request.getHeaders();
        String ip = headers.getFirst("x-forwarded-for");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.indexOf(",") != -1) {
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = headers.getFirst("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddress().getAddress().getHostAddress();
        }
        return ip;

    }

    /**
     * 验证IP是否正确
     * @param ip
     * @param appIp
     * @return
     */
    public static boolean getIpIsBool(String ip,String appIp) {
        boolean fal = false;
        String[] ips =  appIp.split(",");
        for(int i = 0 ;i<ips.length; i++){
            if(ips[i].equals(ip)){
                fal = true;
                break;
            }
        }
        return fal;
    }
}
